package com.soa.ws2http.service;

import java.util.Map;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.soa.ws2http.entity.GatewayService;
import com.soa.ws2http.entity.GatewayWebserviceApi;
import com.soa.ws2http.util.CodeMsg;
import com.soa.ws2http.util.Constant;
import com.soa.ws2http.util.FreemarkerUtil;
import com.soa.ws2http.util.HttpClientCallSoapUtil;
import com.soa.ws2http.util.Json;
import com.soa.ws2http.util.XmlJsonUtil;

/**
 * Created by zx on 2018/6/1.
 */
@Service
@Transactional
public class Webservice2HttpService {
	public final static Logger logger = LoggerFactory.getLogger(Webservice2HttpService.class);
	Gson GSON = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
	@Resource
	StringRedisTemplate stringRedisTemplate;
	@PersistenceContext
	private EntityManager entityManager;

	private Session session;

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public Session getSession() {
		return this.getEntityManager().unwrap(org.hibernate.Session.class);
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public CodeMsg search(String path,String method, Map<String, String> paramMap) {
		com.soa.ws2http.util.CodeMsg codeMsg =CodeMsg.SUCCESS;
		GatewayWebserviceApi gatewayWebserviceApi = this.getGatewayWebserviceApiByPath(path);
		if(gatewayWebserviceApi==null){
			return CodeMsg.API_NULL;
		}
		if(!"1".equals(gatewayWebserviceApi.getState())){
			return CodeMsg.SERVICE_STATE_ERROR;
		}
		try {
			String result="";
			String soapXml = FreemarkerUtil.freemarkerProcess(paramMap, gatewayWebserviceApi.getWsXml());
			if(Constant.soapVersion1_1.equals(gatewayWebserviceApi.getSoapVersion()) || StringUtils.isEmpty(gatewayWebserviceApi.getSoapVersion())){
				result=HttpClientCallSoapUtil.doPostSoap1_1(gatewayWebserviceApi.getWsUrl(), soapXml, gatewayWebserviceApi.getWsAction());
			}else{
				result=HttpClientCallSoapUtil.doPostSoap1_2(gatewayWebserviceApi.getWsUrl(), soapXml, gatewayWebserviceApi.getWsAction());
			}
			if(Constant.soapResult_1.equals(gatewayWebserviceApi.getResultType()) || StringUtils.isEmpty(gatewayWebserviceApi.getResultType())){
				result=XmlJsonUtil.xml2Json(result);
			}
			codeMsg.setResponse(result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			codeMsg=CodeMsg.WEBSERVICE_ERROR;
			codeMsg.setResponse(e.getMessage());
			e.printStackTrace();
		}
		return codeMsg;
	}
	
	public GatewayService getGatewayServiceByPath(String path) {
		GatewayService gatewayService = null;
		String redisKey = GatewayService.class.getSimpleName() + ":path:" + path;
		String gatewayServiceJson = stringRedisTemplate.opsForValue().get(redisKey);
		if (!StringUtils.isEmpty(gatewayServiceJson)) {
			gatewayService = Json.formObject(GatewayService.class, gatewayServiceJson);
		} else {
			Criteria userCriteria = this.getSession().createCriteria(GatewayService.class);
			userCriteria.add(Restrictions.eq("path", path));
			gatewayService = (GatewayService) userCriteria.uniqueResult();
			stringRedisTemplate.opsForValue().set(redisKey, Json.toJson(gatewayService));
			logger.info("成功同步到redsi:   "+redisKey);
		}
		return gatewayService;
	}
	
	
	public GatewayWebserviceApi getGatewayWebserviceApiByPath(String path) {
		GatewayWebserviceApi gatewayWebserviceApi = null;
		String redisKey = GatewayWebserviceApi.class.getSimpleName() + ":path:" + path;
		String gatewayWebserviceApiJson = stringRedisTemplate.opsForValue().get(redisKey);
		if (!StringUtils.isEmpty(gatewayWebserviceApiJson)) {
			gatewayWebserviceApi = Json.formObject(GatewayWebserviceApi.class, gatewayWebserviceApiJson);
		} else {
			Criteria userCriteria = this.getSession().createCriteria(GatewayWebserviceApi.class);
			userCriteria.add(Restrictions.eq("wsPath", path));
			gatewayWebserviceApi = (GatewayWebserviceApi) userCriteria.uniqueResult();
			stringRedisTemplate.opsForValue().set(redisKey, Json.toJsonFilterField(gatewayWebserviceApi,"gatewayWebserviceApiParams"));
			logger.info("成功同步到redsi:   "+redisKey);
		}
		return gatewayWebserviceApi;
	}
}
